<template>
  <div class="com-container">
    <div class="com-chart" ref="hot_ref"></div>
    <span class="iconfont icon-left" @click="toLast" :style="fontsize"
      >&#xe6ef;</span
    >
    <span class="iconfont icon-right" @click="toNext" :style="fontsize"
      >&#xe6ed;</span
    >
    <span class="cat-name" :style="fontsize">{{ catName }}</span>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { getThemeValue } from '../utils/theme_utils';
export default {
  data() {
    return {
      allData: [],
      chartInstance: null,
      currentProduct: 0,
      titleFontsize: 0,
    };
  },

  created() {
    window.addEventListener('resize', this.screenAdapter);
    // 注册回调函数
    this.$socket.registerCallBack('hotData', this.getData);
  },

  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'hotData',
      chartName: 'hotproduct',
      value: '',
    });
    this.screenAdapter();
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.screenAdapter);

    this.$socket.unRegisterCallBack('hotData');
  },

  computed: {
    fontsize() {
      return {
        fontSize: this.titleFontsize + 'px',
        color: getThemeValue(this.theme).titleColor,
      };
    },
    catName() {
      if (!this.allData) return '';
      return this.allData[this.currentProduct]?.name;
    },
    ...mapState(['theme'])
  },

  methods: {
    // init chart
    async initChart() {
      this.chartInstance = this.$echarts.init(this.$refs['hot_ref'], this.theme);
      // handle fixed options
      const initOption = {
        title: {
          text: '‖ 热销商品销售金额占比统计',
          left: 20,
          top: 20,
        },
        legend: {
          top: '15%',
          icon: 'circle',
        },
        tooltip: {
          show: true,
          formatter: (arg) => {
            // console.log(arg)
            const thirdCategory = arg.data.children;
            // 计算出所有三级分类的数值总和
            let total = 0;
            thirdCategory.forEach((item) => {
              total += item.value;
            });
            let retStr = '';
            thirdCategory.forEach((item) => {
              retStr += `
              ${item.name}:${parseInt((item.value / total) * 100) + '%'}
              <br/>
              `;
            });
            return retStr;
          },
        },
        series: [
          {
            type: 'pie',
            label: {
              show: false,
            },
            emphasis: {
              label: {
                show: true,
              },
              labelLine: {
                show: false,
              },
            },
          },
        ],
      };
      this.chartInstance.setOption(initOption);
    },

    // async getData() {
    //   const { data } = await this.$http.get('hotproduct');
    //   this.allData = data;
    //   console.log(data);
    //   this.updateChart();
    // },
    getData(data) {
      // const { data } = await this.$http.get('hotproduct');
      this.allData = data;
      this.updateChart();
    },

    updateChart() {
      const legendArr = this.allData[this.currentProduct].children?.map(
        (item) => item.name
      );
      const seriesArr = this.allData[this.currentProduct].children?.map(
        (item) => {
          return {
            name: item.name,
            value: item.value,
            children: item.children, // 新增加children的原因是为了在tooltip中的formatter的回调函数中,来拿到这个二级分类下的三级分类数据
          };
        }
      );
      // handle data options
      const dataOption = {
        series: [
          {
            data: seriesArr,
          },
        ],
        legend: {
          data: legendArr,
        },
      };
      this.chartInstance.setOption(dataOption);
    },

    screenAdapter() {
      this.titleFontsize = (this.$refs['hot_ref'].offsetWidth / 100) * 3.6;
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: this.titleFontsize,
          },
        },
        legend: {
          itemWidth: this.titleFontsize,
          itemHeight: this.titleFontsize,
          itemGap: this.titleFontsize / 2,
          textStyle: {
            fontSize: this.titleFontsize / 2,
          },
        },
        series: [
          {
            radius: this.titleFontsize * 4.5,
            center: ['50%', '60%'],
          },
        ],
      };
      this.chartInstance.setOption(adapterOption);
      this.chartInstance.resize();
    },

    toNext() {
      this.currentProduct++;
      if (this.currentProduct > this.allData.length - 1) {
        this.currentProduct = 0;
      }
      this.updateChart();
    },

    toLast() {
      if (this.currentProduct === 0) {
        this.currentProduct = this.allData.length - 1;
      } else {
        this.currentProduct--;
      }

      this.updateChart();
    },
  },
  watch: {
    theme () {
      console.log('主题切换了')
      this.chartInstance.dispose() // 销毁当前的图表
      this.initChart() // 重新以最新的主题名称初始化图表对象
      this.screenAdapter() // 完成屏幕的适配
      this.updateChart() // 更新图表的展示
    }
  }
};
</script>

<style scoped lang="scss">
.icon-left {
  position: absolute;
  // z-index: 10;
  top: 50%;
  left: 10%;
  transform: translateY(-50%);
  color: #fff;
  cursor: pointer;
}

.icon-right {
  position: absolute;
  // z-index: 10;
  top: 50%;
  right: 10%;
  transform: translateY(-50%);
  color: #fff;
  cursor: pointer;
}

.cat-name {
  position: absolute;
  left: 80%;
  bottom: 20px;
  color: #fff;
}
</style>
